'use client';

import { useState, useEffect } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import Link from 'next/link';

export default function ResetPasswordConfirmPage() {
  const router = useRouter();
  const searchParams = useSearchParams();
  
  const [email, setEmail] = useState('');
  const [code, setCode] = useState('');
  const [password, setPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState(false);
  const [verificationChecked, setVerificationChecked] = useState(false);
  
  // 从URL参数中获取邮箱和验证码（如果有）
  useEffect(() => {
    const emailParam = searchParams?.get('email');
    const codeParam = searchParams?.get('code');
    
    if (emailParam) setEmail(emailParam);
    if (codeParam) setCode(codeParam);
  }, [searchParams]);
  
  // 验证验证码
  const verifyCode = async () => {
    if (!email || !code) {
      setError('请输入邮箱和验证码');
      return;
    }
    
    setIsLoading(true);
    setError('');
    
    try {
      const response = await fetch(`/api/auth/reset-password?email=${encodeURIComponent(email)}&code=${encodeURIComponent(code)}`);
      const data = await response.json();
      
      if (data.success) {
        setVerificationChecked(true);
      } else {
        setError(data.message || '验证码验证失败，请重新输入');
      }
    } catch (err) {
      console.error('验证码验证失败:', err);
      setError('验证码验证失败，请重新输入');
    } finally {
      setIsLoading(false);
    }
  };
  
  // 重置密码
  const resetPassword = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!email || !code || !password || !confirmPassword) {
      setError('所有字段必须填写');
      return;
    }
    
    if (password !== confirmPassword) {
      setError('两次输入的密码不匹配');
      return;
    }
    
    if (password.length < 8) {
      setError('密码长度必须至少为8个字符');
      return;
    }
    
    setIsLoading(true);
    setError('');
    
    try {
      const response = await fetch('/api/auth/reset-password/confirm', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          email,
          code,
          password
        })
      });
      
      const data = await response.json();
      
      if (data.success) {
        setSuccess(true);
        // 2秒后自动跳转到登录页面
        setTimeout(() => {
          router.push('/auth/login');
        }, 2000);
      } else {
        setError(data.message || '重置密码失败，请重试');
      }
    } catch (err) {
      console.error('重置密码失败:', err);
      setError('重置密码失败，请重试');
    } finally {
      setIsLoading(false);
    }
  };
  
  return (
    <div className="min-h-screen bg-gray-50">
      <div className="flex min-h-screen flex-1 flex-col justify-center px-6 py-12 lg:px-8">
        <div className="sm:mx-auto sm:w-full sm:max-w-sm">
          <h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">
            重置密码
          </h2>
        </div>

        <div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
          {error && (
            <div className="mb-4 p-3 text-sm text-red-700 bg-red-100 rounded-md">
              {error}
            </div>
          )}
          
          {success ? (
            <div className="mb-4 p-3 text-sm text-green-700 bg-green-100 rounded-md">
              <p>密码已成功重置!</p>
              <p>即将跳转到登录页面...</p>
              <div className="mt-4">
                <Link href="/auth/login" className="text-blue-600 hover:text-blue-500">
                  立即前往登录
                </Link>
              </div>
            </div>
          ) : !verificationChecked ? (
            <div>
              <div className="space-y-6">
                <div>
                  <label htmlFor="email" className="block text-sm font-medium leading-6 text-gray-900">
                    邮箱地址
                  </label>
                  <div className="mt-2">
                    <input
                      id="email"
                      name="email"
                      type="email"
                      autoComplete="email"
                      required
                      value={email}
                      onChange={(e) => setEmail(e.target.value)}
                      className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                    />
                  </div>
                </div>
                
                <div>
                  <label htmlFor="code" className="block text-sm font-medium leading-6 text-gray-900">
                    验证码
                  </label>
                  <div className="mt-2">
                    <input
                      id="code"
                      name="code"
                      type="text"
                      required
                      value={code}
                      onChange={(e) => setCode(e.target.value)}
                      className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                    />
                  </div>
                </div>

                <div>
                  <button
                    type="button"
                    onClick={verifyCode}
                    disabled={isLoading}
                    className="flex w-full justify-center rounded-md bg-blue-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                  >
                    {isLoading ? '验证中...' : '验证'}
                  </button>
                </div>
              </div>
              
              <p className="mt-10 text-center text-sm text-gray-500">
                <Link href="/auth/reset-password" className="font-semibold leading-6 text-blue-600 hover:text-blue-500">
                  重新获取验证码
                </Link>
              </p>
            </div>
          ) : (
            <form className="space-y-6" onSubmit={resetPassword}>
              <div>
                <label htmlFor="new-password" className="block text-sm font-medium leading-6 text-gray-900">
                  新密码
                </label>
                <div className="mt-2">
                  <input
                    id="new-password"
                    name="new-password"
                    type="password"
                    autoComplete="new-password"
                    required
                    value={password}
                    onChange={(e) => setPassword(e.target.value)}
                    className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                  />
                </div>
              </div>

              <div>
                <label htmlFor="confirm-password" className="block text-sm font-medium leading-6 text-gray-900">
                  确认新密码
                </label>
                <div className="mt-2">
                  <input
                    id="confirm-password"
                    name="confirm-password"
                    type="password"
                    autoComplete="new-password"
                    required
                    value={confirmPassword}
                    onChange={(e) => setConfirmPassword(e.target.value)}
                    className="block w-full rounded-md border-0 py-1.5 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-blue-600 sm:text-sm sm:leading-6"
                  />
                </div>
              </div>

              <div>
                <button
                  type="submit"
                  disabled={isLoading}
                  className="flex w-full justify-center rounded-md bg-blue-600 px-3 py-1.5 text-sm font-semibold leading-6 text-white shadow-sm hover:bg-blue-500 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {isLoading ? '处理中...' : '重置密码'}
                </button>
              </div>
            </form>
          )}

          {!success && (
            <p className="mt-10 text-center text-sm text-gray-500">
              记起密码了?{' '}
              <Link href="/auth/login" className="font-semibold leading-6 text-blue-600 hover:text-blue-500">
                返回登录
              </Link>
            </p>
          )}
        </div>
      </div>
    </div>
  );
} 